import React, { useEffect, useState } from 'react'
import { Button, message, Modal, Space, Table } from 'antd'
import useGetTableData from './useGetTableData'
import { getRoutesList, addRoutes, editRoutes, delRouteById, getAppList } from '@/api/system'
import SearchForm from '@/components/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import './index.less'
import { IAppSelect, IAppType, IMenuType, IOptionType, ITableData } from './types'
import EditForm from '@/components/EditForm'
import { useFormAdd } from './useFormAdd'
import CustomTable from '@/components/CustomTable'
import { STATUSOPTIONS } from '@/constant'
import { useNavigate } from 'react-router-dom'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [appList, setAppList] = useState<IAppSelect>([])
  const [menuInfo, setMenuInfo] = useState<IMenuType>({ val: 0, info: {} })
  const { tableProps, params, search, reset } = useGetTableData<ITableData>(
    () =>
      new Promise((resolve) =>
        setTimeout(() => {
          resolve({
            code: 200,
            msg: 'c',
            data: [],
          })
        }, 1000),
      ),
    {
      form: form,
      pageSize: 999,
    },
  )
  useEffect(() => {
    getListOfApp()
  }, [])
  const formatList = (list: ITableData[]): IOptionType => {
    return list?.map((item: ITableData) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
        children: Array.isArray(item.children) ? formatList(item.children) : [],
      }
    })
  }
  const onConfirm = async (values: any) => {
    const res = await addRoutes(values)
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search()
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onMenuChange = (val: string | number, info: Record<string, any>) => {
    setMenuInfo({ val, info })
  }
  const onPathChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (menuInfo.val === 0) {
      FormEdit.setFieldValue('fullPath', '/' + event.target.value)
    } else {
      console.log(menuInfo.info)
      FormEdit.setFieldValue('fullPath', menuInfo.info.fullPath + '/' + event.target.value)
    }
  }
  const onEdit = () => {
    navigate('/system/role/edit')
  }
  const onDel = async (id: number) => {
    const res = await delRouteById([id])
    if (res.code === 200) {
      message.success('操作成功')
      search()
    }
  }
  const getListOfApp = async () => {
    const res = await getAppList<IAppType>()
    if (res.code === 200) {
      const data = res.data?.map((item) => {
        return {
          label: item.applicationName,
          value: item.id,
        }
      })
      setAppList(data)
    }
  }
  return (
    <PageContainer className="rolemgr_page">
      <SearchForm
        form={form}
        searchConfig={[
          { label: '角色名称', name: 'org_name', type: 'Select', option: STATUSOPTIONS },
          { label: '所属应用', name: 'app', type: 'Select', option: STATUSOPTIONS },
          { label: '角色名称', name: 'role_name', type: 'Input' },
          { label: '角色状态', name: 'role_type', type: 'Select', option: STATUSOPTIONS },
        ]}
        onFinish={(vals: any) => {
          console.log(vals, 'vals')
          search(vals)
        }}
        onReset={() => {
          reset()
        }}
      ></SearchForm>
      <CustomTable
        extra={
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setIsModalShow(true)
              }}
            >
              新建角色
            </Button>
          </Space>
        }
        columns={useIndexColumns(onEdit, onDel, params)}
        {...tableProps}
        dataSource={[{ id: 1 }]}
      />
      <Modal
        title="新建角色"
        width={550}
        open={isModalShow}
        getContainer={false}
        onOk={() => {
          FormEdit.validateFields().then((values: any) => onConfirm(values))
        }}
        onCancel={onCancel}
      >
        <EditForm
          editConfig={useFormAdd({
            onMenuChange,
            onPathChange,
            data: formatList(tableProps?.dataSource),
            appList,
          })}
          form={FormEdit}
          initialValues={{ type: 'ROUTE', cache: 0 }}
        />
      </Modal>
    </PageContainer>
  )
}

export default Index
